package dd.lo.chapter8;

import javafx.application.Application;
import javafx.concurrent.Task;
import javafx.scene.Scene;
import javafx.scene.image.Image;
import javafx.scene.image.ImageView;
import javafx.scene.input.KeyCode;
import javafx.scene.layout.BorderPane;
import javafx.stage.Stage;
import org.opencv.core.*;
import org.opencv.imgcodecs.Imgcodecs;
import org.opencv.imgproc.Imgproc;

import java.io.ByteArrayInputStream;

/**
 * Chapter8，练习2，Create a program that reads in and displays an image. When the user’s mouse clicks on the image, read in the corresponding pixel values (blue, green, red) and write those values as text to the screen at the mouse location.
 */
public class Exercise2 extends Application {
    private Mat srcImg;

    private ImageView imageView;

    public static void main(String[] args) {
        System.loadLibrary(Core.NATIVE_LIBRARY_NAME);
        launch(args);
    }

    @Override
    public void start(Stage stage) {
        //读取一张图片
        srcImg = Imgcodecs.imread("/Users/kwok/Downloads/男女骑友.png", Imgcodecs.IMREAD_UNCHANGED);
        if (srcImg.empty()) {
            throw new RuntimeException("图片读取失败");
        }
        imageView = new ImageView();
        imageView.setOnMouseClicked(e -> {
            refreshImg(e.getX(), e.getY());
        });
        //imageView放到一个pane的中间
        BorderPane root = new BorderPane();
        root.setCenter(imageView);
        Scene scene = new Scene(root, srcImg.width(), srcImg.height());
        scene.setOnKeyReleased(keyEvent -> {
            //按下esc可以关闭程序
            if (KeyCode.ESCAPE == keyEvent.getCode()) {
                stage.close();
            }
        });
        stage.setScene(scene);
        stage.setTitle("Example4-Origin");
        stage.setResizable(false);
        refreshImg();
        stage.show();
    }

    /**
     * 刷新imageView中的展示画面
     */
    private void refreshImg() {
        refreshImg(null, null);
    }

    private void refreshImg(Double x, Double y) {
        Task<Void> task = new Task<Void>() {
            @Override
            protected Void call() throws Exception {
                Mat copy = srcImg.clone();
                if (null != x && null != y) {
                    double[] p = copy.get(y.intValue(), x.intValue());
                    Imgproc.putText(copy, String.format("(%f, %f, %f)", p[0], p[1], p[2]), new Point(x, y), Imgproc.FONT_HERSHEY_SIMPLEX, 0.4, new Scalar(249, 105, 48), 1, Imgproc.LINE_8);
                    System.out.printf("Click (%f, %f); pixel (blue, green, red) channels: (%f, %f, %f)\n", x, y, p[0], p[1], p[2]);
                }
                MatOfByte buffer = new MatOfByte();
                Imgcodecs.imencode(".jpeg", copy, buffer);
                imageView.setImage(new Image(new ByteArrayInputStream(buffer.toArray())));
                return null;
            }
        };
        new Thread(task).start();
    }
}
